package com.angel.service.ServiceImpl;

import com.angel.bean.Product;
import com.angel.bean.dto.GoodListDto;
import com.angel.bean.dto.PurchaseApplicationDetils;
import com.angel.mapper.ProductDao;
import com.angel.service.ProductService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.angel.bean.PurchaseApplication;
import com.angel.mapper.PurchaseApplicationDao;
import com.angel.service.PurchaseApplicationService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

@Service
public class PurchaseApplicationServiceImpl implements PurchaseApplicationService {

    @Resource
    private PurchaseApplicationDao purchaseApplicationDao;

    @Resource
    private ProductService productService;

    @Override
    public int insert(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.insert(purchaseApplication);
    }

    @Override
    public int insertSelective(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.insertSelective(purchaseApplication);
    }

    @Override
    public int insertList(List<PurchaseApplication> purchaseApplications) {
        return purchaseApplicationDao.insertList(purchaseApplications);
    }

    @Override
    public int update(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.update(purchaseApplication);
    }

    @Override
    public int delete(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.delete(purchaseApplication);
    }

    @Override
    public PurchaseApplication findOne(PurchaseApplication purchaseApplication) {
        List<PurchaseApplication> list =  purchaseApplicationDao.findPurchaseApplication(purchaseApplication);
        if (list == null || list.isEmpty()) {
            return null;
        }
        return list.get(0);
    }

    @Override
    public List<PurchaseApplication> findPurchaseApplication(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.findPurchaseApplication(purchaseApplication);
    }

    @Override
    public List<PurchaseApplicationDetils> finddetilPurchaseApplication(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.finddetilPurchaseApplication(purchaseApplication);
    }


    @Override
    public List<PurchaseApplication> searchPurchaseApplication(PurchaseApplication purchaseApplication) {
        return purchaseApplicationDao.searchPurchaseApplication(purchaseApplication);
    }

    /**
     * @param goodListDtos        进货清单
     * @param purchaseApplication 进货信息单
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    @Override
    public Map detilGoods(List<GoodListDto> goodListDtos, PurchaseApplication purchaseApplication) throws Exception {
        Map<Object, Object> map = new HashMap<>();
        //通过子店id查询商品列表
        Product product = new Product();
        product.setBranId(purchaseApplication.getSubId());
        //子店商品列表
        List<Product> plist = productService.findProduct(product);
        //子店记录不存在的商品,新商品
        List<Product> newProduct = new ArrayList<>();
        //子店记录存在的商品
        List<Product> exProduct = new ArrayList<>();
        //父店商品表
        List<Product> parProduct = new ArrayList<>();
        for (int i = 0; i < goodListDtos.size(); i++) {
            //子店单个商品
            GoodListDto tmp = goodListDtos.get(i);
            boolean isNew = true;
            for (int j = 0; j < plist.size(); j++) {
                Product ptmp = plist.get(j);
                if (ptmp.getProductNo().equals(tmp.getProductNo()) && ptmp.getReserve1().equals(tmp.getPname())) {
                    //子店进货清单的单个商品
                    Product subep = ptmp;
                    int amp = 0;
                    if (subep.getProStock() == null) {
                        amp = tmp.getAmount();
                    } else {
                        amp = subep.getProStock() + tmp.getAmount();
                    }
                    Product upproduct = new Product();
                    //父店商品id
                    upproduct.setProductId(tmp.getProductId());
                    //父店剩余库存
                    upproduct.setProStock(tmp.getProStock() - tmp.getAmount());
                    //设置进货后的库存
                    subep.setProStock(amp);
                    //将该数据放入已存在的商品表
                    subep.setPurchaseDate(new Timestamp(System.currentTimeMillis()));
                    exProduct.add(subep);
                    //更新后的父店库存量数据
                    parProduct.add(upproduct);
                    isNew = false;
                }
            }
            // 子店不存在该商品，属于新商品
            if (isNew) {
                Product newTmp = new Product();
                newTmp.setProductId(tmp.getProductId());
                //父店存在，子店不存在商品
                newTmp = productService.findOne(newTmp);
                newTmp.setProductId(null);
                //设置新商品所属分店
                newTmp.setBranId(purchaseApplication.getSubId());
                int pstok = newTmp.getProStock();
                newTmp.setProStock(tmp.getAmount());
                //存入新商品列表
                newTmp.setPurchaseDate(new Timestamp(System.currentTimeMillis()));
                newProduct.add(newTmp);
                Product upProduct = new Product();
                upProduct.setProductId(tmp.getProductId());
                //更改父店的商品库存
                upProduct.setProStock(pstok - tmp.getAmount());
                parProduct.add(upProduct);
            }
        }

        //更新父店商品装状态
        boolean ispar = true;
        for (int i = 0; i < parProduct.size(); i++) {
            int res = productService.update(parProduct.get(i));
            if (res == 0) {
                ispar = false;
            }
        }
        if (ispar) {
            map.put("ispar", "您的商品更新成功");
        } else {
            Exception e = new Exception("处理失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
        boolean isupex = true;
        for (int j = 0; j < exProduct.size(); j++) {
            int re = productService.update(exProduct.get(j));
            if (re == 0) {
                isupex = false;
                break;
            }
        }
        if (isupex) {
            map.put("isupex", "商品更新成功");
        } else {
            Exception e = new Exception("处理失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
        boolean isnewb = true;
        for (int z = 0; z < newProduct.size(); z++) {
            int rp = productService.insert(newProduct.get(z));
            if (rp == 0) {
                isnewb = false;
                break;
            }
        }
        if (isnewb) {
            map.put("isnewb", "商品更新成功");
        } else {
            Exception e = new Exception("处理失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
        purchaseApplication.setAplicState(2);
        int r = purchaseApplicationDao.update(purchaseApplication);
        if (r != 0) {
            map.put("a", "订单状态更新成功");
        } else {
            Exception e = new Exception("处理失败");
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw e;
        }
        return map;
    }
}
